<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */

namespace App\Model;


use App\Common\Singleton;
use Hyperf\Database\Model\SoftDeletes;
use Hyperf\Database\Schema\Schema;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

class BaseModel extends Model
{
    use Singleton;

    /*
     * 设置软删除
     */
    use SoftDeletes;

    const DELETED_AT = 'delete_time';
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    protected $saas_id;
    protected $dateFormat = 'U';
    protected $tableName = 'default';

    public $timestamps = true;

    public function __construct(array $attributes = [])
    {
        $this->saas_id = get_saas_id();
        $this->connection = get_current_db();
        $this->initTable();
        $this->table = getTable($this->tableName);
        $this->initFillable();
        $this->attributes = ['saas_id'=>$this->saas_id];

        parent::__construct($attributes);
    }

    /**
     * Notes: 根据 Model名字 自动生成tableName
     *        要求 命名规范 例如：MemberPointModel -> member_point
     * Author: Bruce.z
     * DateTime: 2022/6/7 15:12
     */
    private function initTable()
    {
        if($this->tableName == "default"){
            $class = explode( '\\', get_class($this));
            $name = str_replace('Model', '', end($class));
            $this->tableName = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $name));
        }
    }

    /**
     * Notes: 自动生成 除了主键id外 - 覆盖全表的 fillable
     * Author: Bruce.z
     * DateTime: 2022/6/7 15:16
     */
    private function initFillable()
    {
        if(!$this->fillable){
            $key = 'columns_'. $this->tableName;
            $redis = ApplicationContext::getContainer()->get(Redis::class);
            if(!$column = $redis->get($key)){
                $columns = Schema::getColumnListing($this->tableName);
                $columns = array_diff($columns, ['id','delete_time']);
                self::fillable($columns);

                $redis->set($key, serialize($columns));
            }else{
                self::fillable(unserialize($column));
            }
        }
    }

    /**
     * Notes: 过滤表字段数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:13
     * @param $data
     */
    public function filterFields(&$data)
    {
        $data = array_only($data, $this->fillable);
    }

    /**
     * Notes: 添加数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:17
     * @param $data
     * @return BaseModel|\Hyperf\Database\Model\Model
     */
    public function baseAdd($data)
    {
        $data = array_merge($data, $this->attributes);
        $this->filterFields($data);

        return $this->create($data);
    }

    public function batchAdd($data): bool
    {
        $now = time();
        foreach ($data as &$value) {
            $value['create_time'] = $now;
            $value['update_time'] = $now;
            $value = array_merge($value, $this->attributes);
            $this->filterFields($value);
        }

        return $this->insert($data);
    }

    /**
     * Notes: 根据ID编辑数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:19
     * @param $id
     * @param $data
     * @return int
     */
    public function baseEdit($id, $data)
    {
        $conditions = $this->attributes;
        return $this->where($conditions)->where($this->primaryKey, '=', $id)->update($data);
    }

    /**
     * Notes: 根据ID删除数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:22
     * @param $id
     * @return int|mixed
     */
    public function baseRemove($id)
    {
        $conditions = $this->attributes;
        return $this->where($conditions)->where($this->primaryKey, '=', $id)->delete();
    }

    public function getPrimaryKey(): string
    {
        return $this->primaryKey;
    }
}
